import { FastifyInstance } from "fastify";
import { Static, Type } from "@sinclair/typebox";
import { Organization } from "@db";
import { config } from "@config";

const organizationParams = Type.Object({
    organizationId: Type.Number(),
});

export const organization = async (fastify: FastifyInstance) => {
    fastify.get<{
        Params: Static<typeof organizationParams>;
    }>(
        "/organization/:organizationId",
        {
            schema: {
                tags: ["organization"],
                params: organizationParams,
            },
        },
        async (req, res) => {
            const { organizationId } = req.params;

            const organization = await Organization.findOne({
                where: {
                    id: organizationId,
                },
            });

            return res.send({
                ...organization.dataValues,
                photo: organization.photo
                    ? "https://" +
                      config.host +
                      "/files/organizationAvatars/" +
                      organization.photo
                    : null,
                password: undefined,
                createdAt: undefined,
                updatedAt: undefined,
            });
        }
    );
    fastify.get(
        "/organization",
        {
            preHandler: fastify.auth("organization"),
            schema: {
                tags: ["organization"],
            },
        },
        async (req, res) => {
            return res.send({
                ...req.organization.dataValues,
                photo: req.organization.photo
                    ? "https://" +
                      config.host +
                      "/files/organizationAvatars/" +
                      req.organization.photo
                    : null,
                password: undefined,
                createdAt: undefined,
                updatedAt: undefined,
            });
        }
    );
};
